package zuochengyun;

import java.util.LinkedList;
import java.util.Queue;

import javax.xml.soap.Node;

import list.ListNode;
import Tree.TreeNode;

//二叉树的序列化和反序列化
public class SerialTree {

	public StringBuilder serialByPre(TreeNode head){
		if(head == null){
			return new StringBuilder("#!");
		}
		StringBuilder res = new StringBuilder(head.val).append("#");
		res.append(serialByPre(head.left));
		res.append(serialByPre(head.right));
		return res;
	}
	
	
	public TreeNode reconFromPreOrder(String preStr){
		String[] values = preStr.split("!");
		Queue<String> queue = new LinkedList<String>();
		for (int i = 0; i != values.length; i++) {
			queue.offer(values[i]);
		}
		return reconPreOrder(queue);
	}


	private TreeNode reconPreOrder(Queue<String> queue) {
		String value = queue.poll();
		if(value.equals("#")){
			return null;
		}
		TreeNode head = new TreeNode(Integer.valueOf(value));
		head.left = reconPreOrder(queue);
		head.right = reconPreOrder(queue);
		return head;
	}
}
